package com.example.demo.controller;

import com.example.demo.common.entity.JsonResult;
import com.example.demo.common.entity.JsonResultStatus;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * Created by Mojo on 2017/8/29.
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private UserService userService;

	@ApiOperation(value="查询所有用户信息", notes="查询所有用户信息")
	@RequestMapping(method = RequestMethod.GET,value = "/getAllUser")
	public JsonResult getAllUser(@RequestParam(required = true) int pageNum, @RequestParam(required = true) int pageSize){
		JsonResult jsonResult = new JsonResult();
		try{
			jsonResult = userService.getAllUser(pageNum,pageSize);
		}catch (Exception e){
			logger.error("getAllUser 接口异常",e);
			jsonResult = new JsonResult(JsonResultStatus.RET_FAIL,JsonResultStatus.MSG_FAIL);
		}
		return jsonResult;
	}

	@ApiOperation(value="根据username获取用户", notes="根据username获取用户")
	@RequestMapping(method = RequestMethod.GET,value = "/getUser")
	public JsonResult getUser(@RequestParam(required = true) String username){
		JsonResult jsonResult = new JsonResult();
		try{
			User user = userService.getUser(username);
			jsonResult.setData(user);
		}catch (Exception e){
			logger.error("getUser 接口异常",e);
			jsonResult = new JsonResult(JsonResultStatus.RET_FAIL,JsonResultStatus.MSG_FAIL);
		}
		return jsonResult;
	}

	@ApiOperation(value="新增用户", notes="新增用户")
	@RequestMapping(method = RequestMethod.POST,value = "/addUser")
	public JsonResult addUser(@Validated @RequestBody User user){
		JsonResult jsonResult = new JsonResult();
		try{
			jsonResult = userService.addUser(user);
		}catch (Exception e){
			logger.error("addUser 接口异常",e);
			jsonResult = new JsonResult(JsonResultStatus.RET_FAIL,JsonResultStatus.MSG_FAIL);
		}
		return jsonResult;
	}

}
